"""
读取配置文件，下载文件到指定目录
"""
import os
import yaml
from load_docs import Docs

class CreateDocs:

    def __init__(self, config_path):
        with open(config_path, 'r') as f:
            yaml.add_constructor("!include", self.yaml_include)
            self.config = yaml.load(f, Loader = yaml.FullLoader)
    
    # 引用配置文件处理
    def yaml_include(self, loader, node):
            filename = os.path.join(os.path.dirname(loader.name), node.value)
            with open(filename, 'r') as f:
                return yaml.load(f)

    def show_config(self):
        print(self.config)

    def init_doc(self):
        # 生成导航
        navbars = self.config["navbar"]
        nav_list = []
        self.walk_nodes(navbars, nav_list, 0)
        print(nav_list)
        Docs.write_sidebar("_navbar.md", nav_list)
        
    # 遍历节点
    def walk_nodes(self, nodes, nav_list, depth):
        for node in nodes:
            item = {
                "name": node["name"],
                "depth": depth
            }
            if "path" in node:
                item["relative_path"] = node["path"]

            title = Docs.format_title(item)
            nav_list.append(title)
            
            if "docs" in node:
                Docs(node, self.config["gitlab"]).load()
            if "sub" in node and node["sub"] is not None:
                self.walk_nodes(node["sub"], nav_list, depth + 1)

if __name__ == "__main__":
    CreateDocs("source/config_new.yml").init_doc()
